package com.bigdata.wsr.createTable.sink;

import com.bigdata.wsr.createTable.bean.FieldInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;

import java.util.List;
import java.util.Map;

@Slf4j
public class HiveDdlUtil {
    public static String getHiveDdl(String tableName, List<FieldInfo> fieldInfoList, Map<String, String> keyFieldMap) {
        String tableComment = MapUtils.getString(keyFieldMap, "tableComment");

        StringBuilder hiveDdl = new StringBuilder();
        hiveDdl.append("create table qjdods.").append(tableName).append("(").append("\n");
        int size = fieldInfoList.size();
        for (FieldInfo fieldInfo : fieldInfoList) {
            size--;
            if (size == 0) {
                hiveDdl.append(fieldInfo.getFieldName()).append(" ").append(fieldInfo.getFieldType()).append(" comment ").append("'").append(fieldInfo.getFieldComment()).append("'\n")
                        .append(") comment ").append("'").append(tableComment).append("'\n")
                        .append("row format delimited fields terminated by '\\001'\n")
                        .append("stored AS textfile\n")
                        .append("location ").append("'").append("/user/hive/warehouse/qjdods.db/").append(tableName).append("';");
            } else {
                hiveDdl.append(fieldInfo.getFieldName()).append(" ").append(fieldInfo.getFieldType()).append(" comment ").append("'").append(fieldInfo.getFieldComment()).append("'").append(",\n");
            }
        }
        return hiveDdl.toString();
    }


    public static void hiveFieldTypeAdaptor(List<FieldInfo> fieldInfoList, List<FieldInfo> dorisFieldInfoList) {
        for (FieldInfo fieldInfo : fieldInfoList) {
            //对字段类型 做适配
            String fieldType = fieldInfo.getFieldType().toLowerCase();
            if (fieldType.contains("enum") || fieldType.contains("char") || fieldType.contains("text") || fieldType.contains("int") || "date".equals(fieldType)) {
                fieldInfo.setFieldType("string");
            } else if (fieldType.contains("decimal")) {
                fieldInfo.setFieldType("double");
            } else if (fieldType.contains("datetime")) {
                fieldInfo.setFieldType("timestamp");
            }
            dorisFieldInfoList.add(fieldInfo);
        }
    }
}
